package com.zmn.oms.admin.advice;

import com.zmn.oms.common.annotation.PageRequestCas;
import com.zmn.oms.services.interfaces.work.OrderWorkCasOperateService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * 类描述:页面校验
 *
 * @author liuying
 * @date 2020/12/03 4:27 下午
 */
@Aspect
@Configuration
@Slf4j
public class PageRequestCasAspect {

    @Autowired
    private OrderWorkCasOperateService orderWorkCasOperateService;

    @Pointcut("@annotation(com.zmn.oms.common.annotation.PageRequestCas)")
    public void pointCut() {
    }

    @AfterReturning(value = "pointCut() && @annotation(pageRequestCas)", returning = "ret")
    public void pointCut(JoinPoint joinPoint, PageRequestCas pageRequestCas, Object ret) {
        ModelAndView modelAndView = ret instanceof ModelAndView ? ((ModelAndView) ret) : null;
        if (Objects.isNull(modelAndView)) {
            return;
        }

        Object[] args = joinPoint.getArgs();
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        String[] parameterNames = codeSignature.getParameterNames();
        if (parameterNames == null || parameterNames.length < 2) {
            return;
        }

        // 获取订单ID
        Long orderId = null, workId = null;
        if (Objects.equals(parameterNames[0], "orderId")) {
            orderId = Long.parseLong(args[0].toString());
        }
        if (Objects.equals(parameterNames[1], "workId")) {
            workId = Long.parseLong(args[1].toString());
        }

        if (Objects.isNull(orderId) || Objects.isNull(workId)) {
            return;
        }

        String orderCasSign = orderWorkCasOperateService.getOrderCasSign(orderId, workId, pageRequestCas.type());
        log.info("casSign={}", orderCasSign);
        modelAndView.addObject("casSign", orderCasSign);
    }

}
